# Time  ：2021/5/28 8:05
# Author：Houtaroy
from flask import request
from flask_restx import Namespace, Resource
from flask_restx.reqparse import RequestParser

from flask_koala.core.domain import Pageable
from flask_koala.core import RestResult
from flask_koala.auth.handlers import authorization

from .models import User

users = Namespace('users', '用户管理')

users_search_params = RequestParser()
users_search_params.add_argument('username', type=str, help='登录名')
users_search_params.add_argument('name', type=str, help='昵称')
users_search_params.add_argument('gender', type=int, help='性别')
users_search_params.add_argument('pageable', type=Pageable, help='分页对象', default=Pageable(1, 50))

model = User.generate_swagger_model()


@users.route("")
class UserListApi(Resource):
    @authorization("api:users:page")
    @users.expect(users_search_params)
    def get(self):
        params = users_search_params.parse_args()
        return RestResult.success(User.page(params))

    @authorization("api:users:create")
    @users.expect(model)
    def post(self):
        user = User.add(users.payload)
        return RestResult.success(user)


@users.route("/<int:id>")
@users.param('id', '用户id')
class UserApi(Resource):
    @authorization("api:users:load")
    def get(self, id):
        return RestResult.success(User.get(id))

    @authorization("api:users:update")
    def put(self, id):
        User.update(id, users.payload)
        return RestResult.success()

    @authorization("api:users:delete")
    def delete(self, id):
        User.delete(id)
        return RestResult.success()
